<template>
  <AppLayout>
    <div :class="styles['user-edit']">
      <div class="page-header">
        <h1 class="page-title">{{ isEdit ? '编辑用户' : '添加用户' }}</h1>
        <button class="back-btn" @click="goBack">
          <i class="btn-icon">←</i>
          <span>返回</span>
        </button>
      </div>

      <div class="edit-form">
        <form @submit.prevent="saveUser">
          <div class="form-section">
            <h3 class="section-title">基本信息</h3>
            <div class="form-row">
              <div class="form-group">
                <label for="username">用户名 *</label>
                <input id="username" v-model="userForm.username" type="text" required placeholder="请输入用户名">
              </div>
              <div class="form-group">
                <label for="name">姓名 *</label>
                <input id="name" v-model="userForm.name" type="text" required placeholder="请输入姓名">
              </div>
            </div>
            <div class="form-row">
              <div class="form-group">
                <label for="email">邮箱 *</label>
                <input id="email" v-model="userForm.email" type="email" required placeholder="请输入邮箱">
              </div>
              <div class="form-group">
                <label for="phone">手机号</label>
                <input id="phone" v-model="userForm.phone" type="tel" placeholder="请输入手机号">
              </div>
            </div>
          </div>

          <div class="form-section">
            <h3 class="section-title">账户设置</h3>
            <div class="form-row">
              <div class="form-group">
                <label for="role">角色 *</label>
                <select id="role" v-model="userForm.role" required>
                  <option value="">请选择角色</option>
                  <option value="admin">管理员</option>
                  <option value="teacher">教师</option>
                  <option value="student">学生</option>
                </select>
              </div>
              <div class="form-group">
                <label for="status">状态 *</label>
                <select id="status" v-model="userForm.status" required>
                  <option value="">请选择状态</option>
                  <option value="active">活跃</option>
                  <option value="inactive">非活跃</option>
                </select>
              </div>
            </div>
            <div class="form-row" v-if="!isEdit">
              <div class="form-group">
                <label for="password">密码 *</label>
                <input id="password" v-model="userForm.password" type="password" required placeholder="请输入密码">
              </div>
              <div class="form-group">
                <label for="confirmPassword">确认密码 *</label>
                <input id="confirmPassword" v-model="userForm.confirmPassword" type="password" required
                  placeholder="请再次输入密码">
              </div>
            </div>
          </div>

          <div class="form-section">
            <h3 class="section-title">其他信息</h3>
            <div class="form-row">
              <div class="form-group full-width">
                <label for="description">备注</label>
                <textarea id="description" v-model="userForm.description" rows="3" placeholder="请输入备注信息"></textarea>
              </div>
            </div>
          </div>

          <div class="form-actions">
            <button type="button" class="btn-secondary" @click="goBack">
              取消
            </button>
            <button type="submit" class="btn-primary" :disabled="loading">
              {{ loading ? '保存中...' : (isEdit ? '更新' : '创建') }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </AppLayout>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import AppLayout from '@/components/layout/AppLayout.vue'
import { getUserById, createUser, updateUser } from '@/api/user'
import styles from '@/styles/admin/user-edit.module.css'

const route = useRoute()
const router = useRouter()

const loading = ref(false)
const userId = computed(() => route.params.id)
const isEdit = computed(() => !!userId.value)

const userForm = ref({
  username: '',
  name: '',
  email: '',
  phone: '',
  role: '',
  status: 'active',
  password: '',
  confirmPassword: '',
  description: ''
})

const loadUser = async () => {
  if (!isEdit.value) return

  try {
    const response = await getUserById(userId.value)
    const user = response.data
    userForm.value = {
      username: user.username || '',
      name: user.name || '',
      email: user.email || '',
      phone: user.phone || '',
      role: user.role || '',
      status: user.status || 'active',
      password: '',
      confirmPassword: '',
      description: user.description || ''
    }
  } catch (error) {
    console.error('加载用户信息失败:', error)
  }
}

const saveUser = async () => {
  // 验证密码
  if (!isEdit.value && userForm.value.password !== userForm.value.confirmPassword) {
    alert('两次输入的密码不一致')
    return
  }

  loading.value = true
  try {
    const userData = { ...userForm.value }
    delete userData.confirmPassword

    if (isEdit.value) {
      await updateUser(userId.value, userData)
    } else {
      await createUser(userData)
    }

    router.push('/admin/users')
  } catch (error) {
    console.error('保存用户失败:', error)
  } finally {
    loading.value = false
  }
}

const goBack = () => {
  router.push('/admin/users')
}

onMounted(() => {
  loadUser()
})
</script>